package com.project.easy.common.framework.web.service.impl.captcha;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.easy.common.framework.captcha.core.vo.BaseCaptchaConfigVo;
import com.project.easy.common.framework.captcha.core.vo.CaptchResultVo;
import com.project.easy.common.framework.web.entity.FrameworkCaptcha;
import com.project.easy.common.framework.web.mapper.FrameworkCaptchaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Copyright (C), 2000-2022
 * FileName: MysqlSimpleCaptchaProcessor.java
 * Author: yangcaho.cool@gamil.com
 * Date: 2022/5/19 16:20
 * Description: 
*/
@Component
@ConditionalOnBean(value = BaseCaptchaConfigVo.class)
@ConditionalOnProperty(prefix = "yqkj.captcha",  name = "persistence", matchIfMissing = false, havingValue = "mysql")
public class MysqlSimpleCaptchaProcessor extends SimpleCaptchaProcessor {

    @Autowired
    private FrameworkCaptchaMapper frameworkCaptchaMapper;
    /***
     * 持久化
     * @param param 验证编码对象
     * @return 返回是否持久化成功
     */
    @Override
    public Boolean save(CaptchResultVo param) {
        FrameworkCaptcha frameworkCaptcha = new FrameworkCaptcha();
        frameworkCaptcha.setBizType(param.getBizType());
        frameworkCaptcha.setCaptchaKey(param.getCaptchaKey());
        frameworkCaptcha.setContent(param.getText());
        frameworkCaptcha.setResult(param.getResult());
        frameworkCaptcha.setExpireTime(param.getExpireTime());
        this.frameworkCaptchaMapper.insert(frameworkCaptcha);
        return Boolean.TRUE;
    }
    /**
     * @param captchaKey 验证编码KEY
     * @return 返回数据
     */
    @Override
    public CaptchResultVo query(String captchaKey) {
        QueryWrapper<FrameworkCaptcha> frameworkCaptchaQueryWrapper = new QueryWrapper<>();
        frameworkCaptchaQueryWrapper.eq("captcha_key", captchaKey);
        FrameworkCaptcha frameworkCaptcha = this.frameworkCaptchaMapper.selectOne(frameworkCaptchaQueryWrapper);
        if (!Objects.isNull(frameworkCaptcha)) {
            CaptchResultVo captchResultVo = new CaptchResultVo();
            captchResultVo.setBizType(frameworkCaptcha.getBizType());
            captchResultVo.setCaptchaKey(frameworkCaptcha.getCaptchaKey());
            captchResultVo.setText(frameworkCaptcha.getContent());
            captchResultVo.setResult(frameworkCaptcha.getResult());
            captchResultVo.setHasDel(frameworkCaptcha.getHasDel());
            captchResultVo.setExpireTime(frameworkCaptcha.getExpireTime());
            frameworkCaptcha.setHasDel(Boolean.TRUE);
            this.frameworkCaptchaMapper.updateById(frameworkCaptcha);
            return captchResultVo;
        }
        return null;
    }
}
